package com.zlx.controller;


import com.alibaba.fastjson.JSONObject;
import com.zlx.constants.Constant;
import com.zlx.entities.User;
import com.zlx.service.UserService;
import com.zlx.utils.VerifyCode;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author 周罗校
 * @Description
 * @ClassName ImgServlet
 * @date 2020.09.24 12:04:19
 * 该版权归周罗校所有，最终解释权以官方为准
 */

@WebServlet("/img/*")
public class ImgServlet extends BaseServlet {
    UserService userService = new UserService();
    /**
     * @Author 周罗校
     * @Description 头像显示
     * @Param
     * @return
     * @Date 2020.09.24 13:01:29
     **/
    protected void getHead(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String pic = request.getParameter("pic");
        String path = Constant.FILE_PREFIX+pic;
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(path));
        ServletOutputStream outputStream = response.getOutputStream();
        byte[] bytes = new byte[1024];
        int len;
        while ((len = bis.read(bytes)) != -1) {
            outputStream.write(bytes, 0, len);
        }
        outputStream.flush();
    }

    /**
     * @return void
     * @Author 周罗校
     * @Description 文件上传
     * @Param [request, response]
     * @Date 2020.09.24 13:01:59
     **/
    protected void updatePic(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Map<String, String> map = new HashMap<>();
        //为解析类提供配置信息 创建文件上传工厂类
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //创建解析类的实例 传入工厂类获取文件上传对象
        ServletFileUpload sfu = new ServletFileUpload(factory);
        //设置文件最大解析大小(单位：字节)
        sfu.setFileSizeMax(1024 * 1024 * 2);
        //每个表单域中数据会封装到一个对应的FileItem对象上
        PrintWriter out = response.getWriter();
        //图片
        String pic = null;
        //真实地址
        String path;
        try {
            List<FileItem> items = sfu.parseRequest(request);
            for (int i = 0; i < items.size(); i++) {
                FileItem item = items.get(i);
                //isFormField为true，表示这不是文件上传表单域
                if (!item.isFormField()) {
                    String name = item.getName();

                    // xxx.jpg xxx.png
                    String suffix = name.split("\\.")[1];
                    // pic = UUID.randomUUID().toString().replace("-", "") + "." + suffix;
                    pic = System.currentTimeMillis() + "." + suffix;
                    // 123123123.jpg
                    path = Constant.FILE_PREFIX + pic;
                    HttpSession session = request.getSession();
                    User loginUser = (User) session.getAttribute(Constant.LOGIN_USER);
                    userService.updatePicById(pic, loginUser.getId());
                    loginUser.setPic(pic);
                    session.setAttribute(Constant.LOGIN_USER,loginUser);
                    File file = new File(path);
                    if (!file.exists()) {
                        //将文件写出到指定磁盘（即保存图片的服务器）
                        item.write(file);
                    }
                    //返回json
                    map.put("code", "200");
                    map.put("msg", pic);
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
            map.put("code", "500");
            map.put("msg", pic);
        }

        response.getWriter().write(JSONObject.toJSONString(map));
    }
    /**
     * @Author 周罗校
     * @Description 验证码
     * @Param [request, response]
     * @return void
     * @Date 2020.09.24 20:03:21
     **/
    protected void createCheckCode(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        VerifyCode verifyCode = new VerifyCode();
        //获取验证码图片
        BufferedImage image = verifyCode.getImage();
        //把验证码响应回去
        verifyCode.output(image, response.getOutputStream());
        //获取验证码字符串
        String str = verifyCode.getText();
        HttpSession session = request.getSession();
        //把验证码放到会话域中，以便验证码登陆校验
        session.setAttribute(Constant.CHECKCODE_PIC,str);
//        System.out.println(str);
        // 禁止图像缓存
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        // 将图像输出到Servlet输出流中
        ServletOutputStream sos = response.getOutputStream();
        ImageIO.write(image, "jpeg", sos);
        sos.flush();
        sos.close();
    }
}
